package com.hikvision.ae.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author jinjinhui
 * @date 2020/5/15
 */
@Slf4j
public class PythonExecutor {

    public static String executeForString(String fileName, String... params) throws IOException {
        Runtime runtime = Runtime.getRuntime();
        if(!fileName.endsWith(".py")){
            fileName = fileName + ".py";
        }

        String tempPath = System.getProperty("user.dir") + File.separator + "temp" + File.separator;
        File path = new File(tempPath);
        if(!path.exists()){
            path.mkdirs();
        }
        File scriptFile = new File(tempPath + fileName);
        scriptFile.deleteOnExit();
        scriptFile.createNewFile();
        FileCopyUtils.copy(PythonExecutor.class.getResourceAsStream("/algorithm/" + fileName), new FileOutputStream(scriptFile));
        String fullFileName = scriptFile.getAbsolutePath();
        log.info("copy pyth file to path ={}", fullFileName);
        StringBuilder command = new StringBuilder("python ").append(fullFileName);
        for(String param : params){
            command.append(" \"").append(param).append("\"");
        }
        Process process = runtime.exec(command.toString());
        InputStream inputStream = process.getInputStream();
        BufferedReader bufferedReader =new BufferedReader(new InputStreamReader(inputStream));
        String line;
        StringBuilder stringBuilder = new StringBuilder();
        while ((line = bufferedReader.readLine()) != null){
            stringBuilder.append(line);
        }
        return stringBuilder.toString();
    }
}
